<?php

namespace App\Services\Umeng;


use App\Exceptions\ApiExceptions;
use App\Services\AbstractBaseService;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class UmengService extends AbstractBaseService
{

    public function oneclickLogin($mobile_token)
    {
        $host = "http://verify5.market.alicloudapi.com";
        $path = "/api/v1/mobile/info";
        $method = "POST";
        $accept = "application/json";
        $content_type = "application/json; charset=UTF-8";
        $appKey = "204679856"; // 阿里云市场购买应用的appKey
//        $appSecret = "r9866n0kT2I4xJd4NOPaFyfoZFSMnTKpheIAXoNAKV1g7Hd3HSKg8YC20pjPeUVsUvpPl+Oec4rWm8iTpZHMHSsicK9MknLBKQVVd/d0nxlt4/CxNI/EBkBeKtpMhA/pHqUdE1R65M6aN2XRphL1EC+aqqWZWKNCmi2X4xOd7xNWbJwVKCkQDmv9KrANjLQFcNmLxkpvTX1LT9ALfL1G0av5SEbaUj9ll1OZTj18g2TLzURDLCzQ6dL1mSlJs3nSQnpz949HHj4="; // 阿里云市场购买应用的appSecret
        $appSecret = "MFJviRoiUtRpx54ezFuabXhwedM3SK4V"; // 阿里云市场购买应用的appSecret
        $um_appkey = "66a1c6c9940d5a4c499935c2"; // 友盟的appkey

        $timestamp = strval(time() * 1000);
        $uuid = strtoupper(md5(uniqid(rand(), true)));

        $headers = [
            "Accept" => $accept,
            "Content-Type" => $content_type,
            "X-Ca-Version" => "1",
            "X-Ca-Signature-Headers" => "X-Ca-Key,X-Ca-Nonce,X-Ca-Stage,X-Ca-Timestamp,X-Ca-Version",
            "X-Ca-Stage" => "RELEASE",
            "X-Ca-Key" => $appKey,
            "X-Ca-Timestamp" => $timestamp,
            "X-Ca-Nonce" => $uuid,
        ];

        $sign_str = $method . "\n" .
            $accept . "\n" .
            "\n" .
            $content_type . "\n" .
            "\n" .
            "X-Ca-Key:" . $headers["X-Ca-Key"] . "\n" .
            "X-Ca-Nonce:" . $headers["X-Ca-Nonce"] . "\n" .
            "X-Ca-Stage:" . $headers["X-Ca-Stage"] . "\n" .
            "X-Ca-Timestamp:" . $headers["X-Ca-Timestamp"] . "\n" .
            "X-Ca-Version:" . $headers["X-Ca-Version"] . "\n" .
            $path . "?appkey=" . $um_appkey;

        $signature = base64_encode(hash_hmac('sha256', $sign_str, $appSecret, true));
        $headers["X-Ca-Signature"] = $signature;

        $response = Http::withHeaders($headers)
            ->timeout(10)
            ->post($host . $path . "?appkey=" . $um_appkey, [
                'token' => $mobile_token
            ]);
        Log::channel('umeng')->info("返回结果：", $response->json()??'');
        if ($response->successful()) {
            $res = $response->json();
            if ($res['success']) {
                $mobile = $res['data']['mobile'] ?? '';
                if (!$mobile) {
                    throw new ApiExceptions('获取手机号码失败2');
                }
                return $mobile;
            }
            throw new ApiExceptions('获取手机号码失败1');
        } else {
            throw new ApiExceptions('一键登录失败');
        }
    }
}